<?php

namespace app\admin\model\tongcheng;

use addons\tongcheng\model\BaseModel;
use traits\model\SoftDelete;

class ModuleModel extends BaseModel
{

    use SoftDelete;


    // 表名
    protected $name = 'tongcheng_module';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'type_text',
        'status_text',
        'is_show_text',
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);

            // 初始化模块配置
            ModuleConfigModel::create([
                'module_id' => $row[$pk],
            ]);
        });
    }


    public function getTypeList()
    {
        return ['CITY' => __('City'), 'HIT' => __('Hit'), 'REPLACE' => __('Replace')];
    }

    public function getStatusList()
    {
        return ['1' => __('Status 1'), '0' => __('Status 0')];
    }

    public function getIsShowList()
    {
        return ['1' => __('is_show 1'), '0' => __('is_show 0')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list  = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list  = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsShowTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_show']) ? $data['is_show'] : '');
        $list  = $this->getIsShowList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function zone()
    {
        return $this->belongsTo('Zone', 'zone_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function config()
    {
        return $this->hasOne(ModuleConfigModel::class, 'module_id', 'id');
    }

    /**
     * 模块费用规则
     * @param $module_id
     * @return array
     */
    public static function getRule($module_id)
    {
        if (!$module = ModuleModel::where('id', $module_id)->find()) {
            tongcheng_fail('配送模块不存在');
        }
        if (!$module->config) {
            tongcheng_fail('配送模块未配置');
        }

        $rules = [];

        // 基础费
        if ($module->config['base_fee'] > 0) {
            $rules[] = [
                'name'  => '基础费',
                'type'  => 'base',
                'rules' => [
                    [
                        'name'  => '基础费',
                        'value' => $module->config['base_fee'],
                    ],
                ],
            ];
        }

        // 里程费
        if ($module->config['open_range'] && !empty($module->config['range_config'])) {
            $range_config = $module->config['range_config'];
            $range_rule   = [
                'name'  => '配送里程费用',
                'type'  => 'range',
                'rules' => [],
            ];

            $first_rule = array_shift($range_config);
            $last_rule  = array_pop($range_config);

            $range_rule['rules'][] = [
                'name'  => "起步价(包含{$first_rule['end']}公里)",
                'text'  => "{$first_rule['fee']}元",
                'start' => 0,
                'end'   => $first_rule['end'],
                'fee'   => $first_rule['fee'],
                'type'  => 'range_first',
            ];

            foreach ($range_config as $item) {
                $range_rule['rules'][] = [
                    'name'  => "{$item['start']}公里-{$item['end']}公里",
                    'text'  => "{$item['fee']}元",
                    'start' => $item['start'],
                    'end'   => $item['end'],
                    'fee'   => $item['fee'],
                    'type'  => 'range_item',
                ];
            }

            $range_rule['rules'][] = [
                'name'  => "超出{$last_rule['end']}公里",
                'text'  => "+{$last_rule['fee']}元",
                'start' => $last_rule['start'],
                'end'   => $last_rule['end'],
                'fee'   => $last_rule['fee'],
                'type'  => 'range_last',
            ];

            $rules[] = $range_rule;
        }

        // 重量费
        if ($module->config['open_weight'] && !empty($module->config['weight_config'])) {
            $weight_config = $module->config['weight_config'];
            $weight_rule   = [
                'name'  => '重量费用',
                'type'  => 'weight',
                'rules' => [],
            ];

            $last_rule = array_pop($weight_config);
            foreach ($weight_config as $item) {
                $weight_rule['rules'][] = [
                    'name'  => "{$item['start']}公斤-{$item['end']}公斤",
                    'text'  => "{$item['fee']}元",
                    'start' => $item['start'],
                    'end'   => $item['end'],
                    'fee'   => $item['fee'],
                    'type'  => 'weight_item',
                ];
            }

            $weight_rule['rules'][] = [
                'name'  => "超出{$last_rule['end']}公斤",
                'text'  => "+{$last_rule['fee']}元",
                'start' => $last_rule['start'],
                'end'   => $last_rule['end'],
                'fee'   => $last_rule['fee'],
                'type'  => 'weight_last',
            ];

            $rules[] = $weight_rule;
        }

        // 时段费
        if ($module->config['open_surcharge'] && !empty($module->config['surcharge_config'])) {
            $surcharge_config = $module->config['surcharge_config'];
            $surcharge_rule   = [
                'name'  => '特殊时段费用',
                'type'  => 'surcharge',
                'rules' => [],
            ];

            foreach ($surcharge_config as $item) {
                // 未开启
                if (!$item['status']) {
                    continue;
                }

                $surcharge_rule['rules'][] = [
                    'name'      => "{$item['name']} {$item['start']} - {$item['end']}",
                    'text'      => "{$item['fee']}元",
                    'item_name' => $item['name'],
                    'start'     => $item['start'],
                    'end'       => $item['end'],
                    'fee'       => $item['fee'],
                    'type'      => 'surcharge_item',
                ];
            }

            $rules[] = $surcharge_rule;
        }

        // 超时理赔费
        if ($module->config['open_claim'] && !empty($module->config['claim_time_config']) && !empty($module->config['claim_money_config'])) {
            $claim_rule = [
                'name'  => '超时理赔费用',
                'type'  => 'claim',
                'rules' => [],
            ];

            // 距离预估时间
            $claim_time_config = $module->config['claim_time_config'];
            $last_rule         = array_pop($claim_time_config);
            foreach ($claim_time_config as $item) {
                $claim_rule['rules'][] = [
                    'name'      => "距离在{$item['distance']}公里内，预估时间{$item['minutes']}分钟",
                    'text'      => "+{$item['minutes']}分钟",
                    'item_name' => '距离预估时间',
                    'distance'  => $item['distance'],
                    'minutes'   => $item['minutes'],
                    'type'      => 'claim_time',
                ];
            }
            $claim_rule['rules'][] = [
                'name'      => "当距离等于且超过{$last_rule['distance']}公里时，每公里预估时间{$last_rule['minutes']}分钟",
                'text'      => "+{$last_rule['minutes']}分钟",
                'item_name' => '距离预估时间',
                'distance'  => $last_rule['distance'],
                'minutes'   => $last_rule['minutes'],
                'type'      => 'claim_time',
            ];

            // 高峰时段
            if (!empty($module->config['claim_peak_config'])) {
                foreach ($module->config['claim_peak_config'] as $item) {
                    $claim_rule['rules'][] = [
                        'name'      => "时间在{$item['time_range'][0]} - {$item['time_range'][1]}时，增加时间{$item['minutes']}分钟",
                        'text'      => "+{$item['minutes']}分钟",
                        'item_name' => '高峰时段时间',
                        'start'     => $item['time_range'][0],
                        'end'       => $item['time_range'][1],
                        'minutes'   => $item['minutes'],
                        'type'      => 'claim_peak',
                    ];
                }
            }

            // 超时理赔金额
            foreach ($module->config['claim_money_config'] as $item) {
                $claim_rule['rules'][] = [
                    'name'      => "骑手完成订单延时{$item['minutes']}分钟，赔偿{$item['money']}元",
                    'text'      => "{$item['money']}元",
                    'item_name' => '距离预估时间',
                    'minutes'   => $item['minutes'],
                    'money'     => $item['money'],
                    'type'      => 'claim_time',
                ];
            }

            $rules[] = $claim_rule;
        }

        return $rules;
    }
}
